#include "thread.h"
#include "currentThread.h"
#include <semaphore.h>
namespace TinyRPC{

std::atomic<int> Thread::NumOfThreads(0);

Thread::Thread(ThreadFunc task, const std::string& name)
: m_task(task)
, m_name(name)
, m_tid(0)
, m_state(ThreadState::Init)
{
    NumOfThreads ++;
    if(name ==""){
        setDefaultName();
    }
}

pid_t Thread::getTid(){
    return m_tid;
}


std::string Thread::getName(){
    return m_name;
}

void Thread::start(){
    sem_t sem;
    sem_init(&sem, 0, 0);
    auto threadFunc = [&](){
        m_tid = CurrentThread::Tid();
        sem_post(&sem);
        m_task();
    };
    m_thread = std::unique_ptr<std::thread>(new std::thread(threadFunc));
    // 一定要等到获取tid之后才继续执行
    sem_wait(&sem);
    sem_destroy(&sem);
}

void Thread::setDefaultName(){
    int num = NumOfThreads;

    char buf[32]  = {0};
    snprintf(buf,sizeof(buf),"Thread%d", num);
    m_name = std::string(buf);

}

void Thread::join(){
    if(m_thread->joinable()){
        m_state = ThreadState::Join;
        m_thread->join();
    }
}
void Thread::detach(){
    // 已经join的线程或者已经detach的线程无法joinable
    if(m_thread->joinable()){
        m_state = ThreadState::Detach;
        m_thread->detach();
    }
}
    
}
